﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Table;
using Table.DataModel;

namespace UI
{
    /// <summary>
    /// 自走棋英雄的职业，如果表数据增加新的职业，不会影响代码的功能，对应表 AutoChessGroup 中的 type
    /// </summary>
    public enum JobFilterType
    {
        all = 0,
        animal = 1, // 动物之力
        natrual = 2, // 自然之力
        superman = 3, // 超人之力
        combat = 4, // 格斗技巧
        sword = 5, // 剑道技巧
        shooter = 6 // 射击技巧
    }

    /// <summary>
    /// 自走棋英雄的阵营，如果表数据增加新的职业，不会影响代码的功能，对应表 AutoChessGroup 中的 type
    /// </summary>
    public enum CampFilterType
    {
        all = 0,
        strawHat = 1, // 同伴激励 草帽
        CP9 = 2, // 六式 cp9
        impeldown = 3, // 无畏 推进城
        marine = 4, // 戒备森严 海军
        seven = 5, // 雄踞一方 七武海
        pirates = 6, // 掠夺 海盗
        horribleShip = 7, // 诡诈 恐怖船
        god = 8, // 神之怒 神
        fishman = 9, // 海之祝福 鱼人
        whiteBeard = 10 // 白胡子
    }

    public class AutoChessHeroQueryData
    {
        /// <summary>
        /// 职业
        /// </summary>
        public List<int> jobs = new List<int>();
        /// <summary>
        /// 阵营
        /// </summary>
        public List<int> camps = new List<int>();

        /// <summary>
        /// 属性组 Id
        /// </summary>
        public List<int> groupId = new List<int>();

        /// <summary>
        /// 稀有度
        /// </summary>
        public int rare; //0 全部稀有度；1 普通；2 罕见；3 稀有；4 神话；5 传说
        /// <summary>
        /// AutoChessHero 中的 Id
        /// </summary>
        public int heroId;
        /// <summary>
        /// 每个英雄的棋的 id
        /// </summary>
        public int chessId;
    }

    public class AutoChessHerosSubPage : SubContentBase
    {
        public GameObject heroCell;
        public Transform heroCellsParent;
        public Dropdown rareDropdown;
        public Dropdown campDropdown;
        public Dropdown jobDropdown;
        public GameObject detailPanelMask;
        public GameObject buffDetailPanel;
        public GameObject skillDetailPanel;
        public NormalInfinityScrollView scrollView;

        /// <summary>
        /// 所有自走棋英雄
        /// </summary>
        public static List<AutoChessHeroQueryData> allHeros;

        /// <summary>
        /// 筛选的结果
        /// </summary>
        public static List<AutoChessHeroQueryData> heroQueryResult;

        public static bool isDefaultResult = true;

        public static List<AutoChessHeroQueryData> HerosNeedToShow
        {
            get
            {
                return isDefaultResult ? allHeros : heroQueryResult;
            }
        }

        public static Action OnHideDetailPanel;

        /// <summary>
        /// 当前稀有度筛选条件
        /// </summary>
        private int currentRare = 0;

        /// <summary>
        /// 当前阵营筛选条件
        /// </summary>
        private int currentCampFilterType = 0;

        /// <summary>
        /// 当前职业筛选条件
        /// </summary>
        private int currentJobFilterType = 0;

        // Use this for initialization
        void Start()
        {
            SetDropDownContent();
        }

        /// <summary>
        /// 分类查找
        /// </summary>
        /// <param name="rare">稀有度（品质）筛选条件，0 表示所有稀有度</param>
        /// <param name="campType">阵营筛选条件</param>
        /// <param name="jobType">职业筛选条件</param>
        public void QueryByFilter()
        {
            if (heroQueryResult == null)
            {
                int heroCount = TableDataManager.Instance.tableAutoChessHeroDao.CacheList.Count;
                heroQueryResult = new List<AutoChessHeroQueryData>(heroCount);
            }
            else
            {
                heroQueryResult.Clear();
            }

            // 如果使用默认的筛选条件：所有品质 && 所有职业 && 所有阵营，直接显示所有英雄
            if (currentRare == 0 && currentCampFilterType == (int)CampFilterType.all && currentJobFilterType == (int)JobFilterType.all)
            {
                isDefaultResult = true;
                scrollView.Setup(allHeros.Count);
                scrollView.InternalReload();
                scrollView.RefreshCurrentPanel();
                heroCellsParent.localPosition = new Vector3(heroCellsParent.localPosition.x, heroCellsParent.localPosition.y, 0f);
                return;
            }
            else
            {
                isDefaultResult = false;
            }

            foreach (var heroCell in allHeros)
            {
                bool isRareMatched = false;
                if (currentRare == 0 || heroCell.rare == currentRare)
                {
                    isRareMatched = true;
                }

                bool isCampMatched = false;
                if (currentCampFilterType == (int)CampFilterType.all || heroCell.camps.Contains(currentCampFilterType))
                {
                    isCampMatched = true;
                }

                bool isJobMatched = false;
                if (currentJobFilterType == (int)JobFilterType.all || heroCell.jobs.Contains(currentJobFilterType))
                {
                    isJobMatched = true;
                }

                // 与条件匹配
                if (isRareMatched && isCampMatched && isJobMatched)
                {
                    heroQueryResult.Add(heroCell);
                }
            }

            // 不根据品质筛选英雄时，需要根据品质对查询结果排序
            if (currentRare == 0)
            {
                heroQueryResult.Sort((AutoChessHeroQueryData a, AutoChessHeroQueryData b) =>
                {
                    if (a.rare > b.rare)
                        return -1;
                    else if (a.rare < b.rare)
                        return 1;
                    else
                        return 0;
                });
            }

            // 重新刷新 ScrollView
            scrollView.Setup(heroQueryResult.Count);
            scrollView.InternalReload();
            scrollView.RefreshCurrentPanel();
            heroCellsParent.localPosition = new Vector3(heroCellsParent.localPosition.x, heroCellsParent.localPosition.y, 0f);
        }

        /// <summary>
        /// 展示页面
        /// </summary>
        public override void OnShowTab()
        {
            this.gameObject.SetActive(true);

            int heroCount = TableDataManager.Instance.tableAutoChessHeroDao.CacheList.Count;
            allHeros = new List<AutoChessHeroQueryData>(heroCount);
            for (int i = 0; i < heroCount; i++)
            {
                TableAutoChessHero heroData = TableDataManager.Instance.tableAutoChessHeroDao.CacheList[heroCount - 1 - i];

                // 获取英雄的相关数据
                AutoChessHeroQueryData queryData = new AutoChessHeroQueryData();
                queryData.rare = heroData.rare; // 品质
                queryData.heroId = heroData.heroId; // 英雄 id
                queryData.chessId = heroData.chessId; // 英雄对应的棋的 id
                int[] heroGroupIds = ParseHeroGroups(heroData.acHeroGroups);
                for (int j = 0; j < heroGroupIds.Length; j++) // 阵营和职业的 buff
                {
                    TableAutoChessGroup groupData = TableDataManager.Instance.tableAutoChessGroupDao.GetById(heroGroupIds[j]);
                    queryData.groupId.Add(groupData.acHeroGroup);
                    // 这是一条阵营数据
                    if (groupData.groupType == 0)
                    {
                        queryData.camps.Add(groupData.type);
                    }
                    // 这是一条职业数据
                    else if (groupData.groupType == 1)
                    {
                        queryData.jobs.Add(groupData.type);
                    }
                    else
                    {
                        ExLog.LogError("表数据出现错误！可能是表 AutoChessGroup 的 groupType 出现错误！主键 id 为：" + heroGroupIds[i]);
                        continue;
                    }
                }

                allHeros.Add(queryData);
            }

            // 所有英雄只需要排一次序
            allHeros.Sort((AutoChessHeroQueryData a, AutoChessHeroQueryData b) =>
            {
                if (a.rare > b.rare)
                    return -1;
                else if (a.rare < b.rare)
                    return 1;
                else
                    return 0;
            });

            scrollView.Setup(allHeros.Count);
            scrollView.InternalReload();
            scrollView.RefreshCurrentPanel();
            heroCellsParent.localPosition = new Vector3(heroCellsParent.localPosition.x, heroCellsParent.localPosition.y, 0f);
        }

        public override void ReShowTab()
        {
            base.ReShowTab();
            this.gameObject.SetActive(true);
        }

        public override void CloseTab()
        {
            base.CloseTab();
            this.gameObject.SetActive(false);
        }

        public override void OnPageClose()
        {
            base.OnPageClose();
            // 静态区数据要清除、重置
            allHeros.Clear();
            if (heroQueryResult != null)
                heroQueryResult.Clear();
            isDefaultResult = true;
        }

        /// <summary>
        /// 设置筛选下拉框
        /// </summary>
        private void SetDropDownContent()
        {
            List<string> raresDesc = new List<string>();
            List<string> campsDesc = new List<string>();
            List<string> jobsDesc = new List<string>();

            raresDesc.Add(TableTextBlo.GetText("ACExplainPageHeroSubPageAllRare"));
            foreach (var rareData in TableDataManager.Instance.tableAutoChessHeroRareDao.CacheList)
            {
                raresDesc.Add(rareData.rareDesc);
            }
            rareDropdown.ClearOptions();
            rareDropdown.AddOptions(raresDesc);

            campsDesc.Add(TableTextBlo.GetText("ACExplainPageHeroSubPageAllCamps"));
            jobsDesc.Add(TableTextBlo.GetText("ACExplainPageHeroSubPageAllJobs"));
            foreach (var groupData in TableDataManager.Instance.tableAutoChessGroupDao.CacheList)
            {
                if (groupData.groupType == 1)
                {
                    jobsDesc.Add(groupData.groupSkillName);
                }
                else if (groupData.groupType == 0)
                {
                    campsDesc.Add(groupData.groupDesc);
                }
                else
                {
                    Debug.LogError("表 AutoChessGroup 中的 groupType 组类型错误！");
                }
            }

            if (campsDesc.Count - 1 != (int)CampFilterType.whiteBeard || jobsDesc.Count - 1 != (int)JobFilterType.shooter)
            {
                ExLog.LogWarning("注意，表 AutoChessGroup 中阵营或职业的数量与代码中的枚举不一致！但是这不会影响功能。");
            }

            campDropdown.ClearOptions();
            campDropdown.AddOptions(campsDesc);

            jobDropdown.ClearOptions();
            jobDropdown.AddOptions(jobsDesc);
        }

        /// <summary>
        /// 解析 buff 组的字符串
        /// </summary>
        /// <param name="heroGroups"></param>
        /// <returns></returns>
        private int[] ParseHeroGroups(string heroGroups)
        {
            string[] subStrings = heroGroups.Split(';');
            if (subStrings.Length <= 0)
            {
                ExLog.LogError("解析表 autoChessHero 的数据出错！可能是英雄属性组没有填写数据！");
                int[] allGroups = { 1 };
                return allGroups;
            }
            else
            {
                int[] allGroups = new int[subStrings.Length];
                for (int i = 0; i < subStrings.Length; i++)
                {
                    allGroups[i] = int.Parse(subStrings[i]);
                }
                return allGroups;
            }
        }

        public void OnSelectRareFilter(int index)
        {
            currentRare = index;
            QueryByFilter();
        }

        public void OnSelectCampFilter(int index)
        {
            currentCampFilterType = index;
            QueryByFilter();
        }

        public void OnSelectJobFilter(int index)
        {
            currentJobFilterType = index;
            QueryByFilter();
        }

        public void HideAllDetailPanels()
        {
            scrollView.scrollRect.vertical = true;
            detailPanelMask.SetActive(false);
            buffDetailPanel.SetActive(false);
            skillDetailPanel.SetActive(false);
            OnHideDetailPanel();
        }

        public void HideBuffDetailPanel()
        {
            scrollView.scrollRect.vertical = true;
            detailPanelMask.SetActive(false);
            buffDetailPanel.SetActive(false);
        }

        public void HideSkillDetailPanel()
        {
            scrollView.scrollRect.vertical = true;
            detailPanelMask.SetActive(false);
            skillDetailPanel.SetActive(false);
        }
    }
}
